<!-- 部门管理 -->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import { ElTree, ElInput, ElDivider, ElMessage } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Write, Detail } from './components'
import { Dialog } from '@/components/Dialog'
import {
  sysOrgDataList,
  sysDepartmentDataList,
  sysUserDataList,
  sysDepartmentDeleteById,
  sysDepartmentSaveOrUpdate
} from '@/api/backstage'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { getFirstNode } from '@/utils/tree'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    const res = await sysDepartmentDataList({
      orgId: unref(currentNodeKey),
      ...unref(searchParams)
    })
    return {
      list: res.data || []
    }
  },
  fetchDelApi: async () => {
    const res = await sysDepartmentDeleteById({ id: unref(delId) })
    return !!res
  }
})
const { loading, dataList } = tableState
const { getList, delList } = tableMethods

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<any>()
const actionType = ref('')
const userList = ref<any[]>([])

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      remove: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'orgId',
    label: '机构id',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'orgName',
    label: '机构名称',
    form: {
      remove: true
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'parentName',
    label: '父级部门',
    search: {
      hidden: true
    },
    form: {
      componentProps: {
        disabled: true,
        placeholder: '无父级部门'
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'name',
    label: '部门名称'
  },
  {
    field: 'coment',
    label: '描述信息',
    search: {
      hidden: true
    }
  },
  {
    field: 'leader',
    label: '部门主管',
    search: {
      hidden: true
    },
    form: {
      remove: true
    }
  },
  {
    field: 'leaderId',
    label: '部门主管',
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        props: {
          label: 'nickname',
          value: 'id',
          key: 'id'
        }
      },
      optionApi: async () => {
        const res = await sysUserDataList({ orgId: unref(currentNodeKey) })
        userList.value = res.data
        return res.data
      }
    },
    detail: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'sortOrder',
    label: '显示排序',
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 1,
      componentProps: {
        min: 0
      }
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    search: {
      hidden: true
    },
    form: {
      remove: true
    }
  },
  {
    field: 'createUser',
    label: '创建人',
    search: {
      hidden: true
    },
    form: {
      remove: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'updateTime',
    label: '更新时间',
    search: {
      hidden: true
    },
    form: {
      remove: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'updateUser',
    label: '修改人',
    search: {
      hidden: true
    },
    form: {
      remove: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      remove: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <BaseButton type="primary" link onClick={() => AddAction(row)}>
                新增
              </BaseButton>
              <BaseButton type="primary" link onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" link onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" link onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<any[]>([])
const fetchDepartment = async () => {
  const res = await sysOrgDataList({})
  // console.log(departmentList.value)
  // currentNodeKey.value = (res.data[0] && res.data[0]?.children && res.data[0].children[0].id) || ''
  if (res.data.length > 0) {
    departmentList.value = res.data
    const nodeData: any = (res.data.length > 0 && getFirstNode(res.data)) || null
    currentNodeKey.value = nodeData.id || ''
    await nextTick()
    // 设置初始选中的节点
    unref(treeEl)?.setCurrentKey(currentNodeKey.value)
    getList()
  } else {
    departmentList.value = []
  }
}

//将树结构加一个属性parent字段，方便后续操作
// const cgTree = (data) => {
//   for (let i = 0; i < data.length; i++) {
//     if (data[i].children && data[i].children.length > 0) {
//       data[i].disabled = true
//       cgTree(data[i].children)
//     }
//   }
//   return data
// }
fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: any) => {
  // if (data.children) return
  currentNodeKey.value = data.id
  getList()
}

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}

const AddAction = (row: any) => {
  dialogTitle.value = t('exampleDemo.add')
  const parent = row ? { parentId: row.id, parentName: row.name } : undefined
  currentRow.value = {
    orgId: currentNodeKey.value,
    ...parent
  }
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)

const delId = ref('')
const delData = async (row?: any) => {
  if (row.children.length > 0) {
    ElMessage.error('该部门下还有子级，不能删除')
    return
  }
  delId.value = row.id
  delLoading.value = true

  await delList(1).finally(() => {
    delLoading.value = false
  })
}

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  console.log('action', currentRow.value)
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      if (formData.leaderId) {
        formData.leader =
          userList.value.find((item) => item.id === formData.leaderId)?.nickname || ''
      }
      console.log('保存提交', formData)
      const res = await sysDepartmentSaveOrUpdate(formData)
      if (res) {
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}

const ElTreeProp = {
  children: 'children',
  label: 'name',
  value: 'id'
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px">
      <div class="flex justify-center items-center">
        <ElInput v-model="currentDepartment" class="flex-[2]" placeholder="机构" clearable />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="ElTreeProp"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      />
    </ContentWrap>
    <ContentWrap class="flex-[1]">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
        :operationAdd="true"
        :operation-del="false"
        @add="AddAction"
        @batch-del="delData"
      />

      <Table
        node-key="id"
        default-expand-all
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
